<?php
class Pageley_Tag_Echo extends Pageley_Tag_Abstract {
    
    private $text;
    private $escape;
    private $limitCharacters;
    
    public function execute() {
        $text = $this->applyLimitCharacters($this->text);
        if($this->escape) {
            echo htmlspecialchars($text);
        } else {
            echo $text;
        }
    }
    
    private function applyLimitCharacters($text) {
        $result = "";
        if($this->limitCharacters > 0) {
            $lines = Pageley_Util_String::split($text, "\n");
            foreach($lines as $line) {
                $remainder = $line;
                while(Pageley_Util_String::length($remainder) > $this->limitCharacters) {
                    $length = $this->limitCharacters;
                    $fragment = Pageley_Util_String::substring($remainder, 0, $this->limitCharacters);
                    $spacePos = Pageley_Util_String::lastIndexOf($fragment, " ");
                    if($spacePos !== false) {
                        $length = $spacePos + 1;
                    }
                    $result .= Pageley_Util_String::substring($remainder, 0, $length) . "\n  ";
                    $remainder = Pageley_Util_String::substring($remainder, $length);
                }
                $result .= $remainder . "\n";
            }
        } else {
            $result = $text;
        }
        return $result;
    }
    
    public function setText($text) {
        $this->text = $text;
    }
    
    public function setEscape($escape) {
        $this->escape = $escape;
    }
    
    public function setLimitCharacters($limitCharacters) {
        $this->limitCharacters = $limitCharacters;
    }
}